// import Session from "js-cookie";
import { ElMessage, ElMessageBox } from "element-plus";
import userStore from "@/store/userStore.js";

import router from "@/router";
import { Session, Local } from "@/utils/storage";
import {
  loginApi,
  loginByCardApi,
  refreshTokenApi,
  getUserInfoApi,
  getAccessMenusApi,
  logoutApi,
  updatePwdApi,
} from "@/api/auth";

const TokenKey = "AccessToken";
const RefreshTokenKey = "RefreshToken";
export const AUTH_MENUS = "AUTH_MENUS";
export const AUTH_USER = "AUTH_USER";

const modules = import.meta.glob("../views/**/**.vue");

export default function useAuths(opt) {
  const store = userStore();
  const defaultOpt = {
    loginUrl: "/login", // 登录页跳转url 默认: /login
    loginReUrl: "", // 登录页登陆成功后带重定向redirect=的跳转url 默认为空
    homeUrl: "/home", // 主页跳转url 默认: /home
    otherQuery: {}, // 成功登录后携带的（除redirect外）其他参数
  };

  let option = {
    ...defaultOpt,
    ...opt,
  };

  // 获取token
  const getToken = () => {
    return Session.get(TokenKey);
  };

  // 获取刷新token
  const getRefreshToken = () => {
    return Session.get(RefreshTokenKey);
  };

  // 存储token到Session
  const setToken = (token, refreshToken) => {
    if (token == null) {
      return false;
    }
    Session.set(TokenKey, token);
    if (RefreshTokenKey) Session.set(RefreshTokenKey, refreshToken);
    return true;
  };

  // 删除token
  const removeToken = () => {
    Session.remove(TokenKey);
    Session.remove(RefreshTokenKey);
    return true;
  };

  // 退出登录
  const logoutFun = async () => {
    let flag = true;
    try {
      await logoutApi();
    } catch (error) {
      flag = await ElMessageBox.confirm(
        `退出登录失败，是否强制退出？`,
        "提示",
        {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          type: "warning",
        }
      )
        .then(() => {
          return true;
        })
        .catch(() => {
          //取消
          return false;
        });
    }
    if (flag) {
      clearStorage();
    }
  };

  // 清空本地存储的信息
  const clearStorage = () => {
    Session.clear();
    Local.clear();
    removeToken();
    window.location.reload();
    // Session.set("vuex", null);
  };

  // 刷新token
  const refreshToken = async () => {
    try {
      const token = getRefreshToken();
      setToken(token);
      let res = await refreshTokenApi();
      const { accessToken, refreshToken } = res;
      setToken(accessToken, refreshToken);
      return true;
    } catch (error) {
      logoutFun();
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject("登出");
    }
  };

  // 用户名密码登录
  const loginFun = async (params) => {
    const res = await loginApi(params);
    loginSuccess(res);
    return res;
  };

  // 刷卡登录
  const loginByCard = async (params) => {
    const res = await loginByCardApi(params);
    loginSuccess(res);
    return res;
  };

  // 用户更新密码
  const updatePwd = async (params) => {
    const res = await updatePwdApi(params);
    // 用户更新完自己的密码之后退出登录
    logoutFun();
    return res;
  };

  // 获取用户基本信息、角色、菜单权限
  const getUserInfo = async () => {
    try {
      let result = await getUserInfoApi();
      store.setUserInfo(result);
      return result;
    } catch (error) {
      return {};
    }
  };

  // 遍历树动态注册组件
  const treeIterator = (menu) => {
    const menuList = JSON.parse(JSON.stringify(menu));
    return menuList.map((item) => {
      return {
        ...item,
        path: "/" + item.path,
        component: item.component
          ? modules[`../views/${item.component}.vue`]
          : null,
        // children字段写入
        children: item.children ? treeIterator(item.children, true) : [],
      };
    });
  };
  // 获取动态菜单列表
  const getAccessMenus = async () => {
    const res = await getAccessMenusApi();
    const menus = treeIterator(res);
    // 存储菜单
    store.setAccessMenus(menus);
    return menus;
  };

  // 登录成功之后的操作
  const loginSuccess = async (res) => {
    const { accessToken, refreshToken } = res;
    setToken(accessToken, refreshToken);

    try {
      const accessMenus = await getAccessMenus(); // 动态路由菜单
      if (!accessMenus.length) {
        ElMessage({
          message: "登录失败，用户无菜单权限",
          type: "error",
          duration: 2000,
        });
        router.replace({ path: option.loginUrl }); // 默认 /login
        return;
      }

      // 存储用户信息
      await getUserInfo(); // 用户信息
      // 存储租户ID 当前版本后端暂时未设置
      // Session.set('tenantId', result.user.tenantId)
      // 登录成功后 路由跳转
      router.replace({
        path: option.loginReUrl ? option.loginReUrl : option.homeUrl,
        query: option.otherQuery,
      });
    } catch (error) {
      removeToken();
      return false;
    }
  };

  return {
    getToken,
    setToken,
    removeToken,
    loginFun,
    loginByCard,
    refreshToken,
    getUserInfo,
    getAccessMenus,
    logoutFun,
    updatePwd,
    clearStorage,
  };
}
